package com.sina.oasis.crackme

import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.lang.StringBuilder
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

class MainActivity : AppCompatActivity() {
    private var editUserName: EditText? = null
    private var editSn: EditText? = null
    private var btnRegister: Button? = null
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setTitle(R.string.unregister)
        editUserName = findViewById(R.id.edit_username)
        editSn = findViewById(R.id.edit_sn)
        btnRegister = findViewById(R.id.button_register)
        btnRegister?.setOnClickListener {
            if (!checkSN(
                    editUserName!!.text.toString().trim { it <= ' ' },
                    editSn!!.text.toString().trim { it <= ' ' })
            ) {
                Toast.makeText(
                    this@MainActivity,
                    R.string.unsuccessed, Toast.LENGTH_SHORT
                ).show()
            } else {
                Toast.makeText(
                    this@MainActivity,
                    R.string.successed, Toast.LENGTH_SHORT
                ).show()
                btnRegister?.isEnabled = false
                setTitle(R.string.registered)
            }
        }
    }

    private fun checkSN(userName: String?, sn: String?): Boolean {
        try {
            if (userName == null || userName.isEmpty()) return false
            if (sn == null || sn.length != 16) return false
            val digest = MessageDigest.getInstance("MD5")
            digest.reset()
            digest.update(userName.toByteArray())
            val bytes = digest.digest()
            val hexstr = toHexString(bytes, "")
            val sb = StringBuilder()
            var i = 0
            while (i < hexstr.length) {
                sb.append(hexstr[i])
                i += 2
            }
            val userSN = sb.toString()
            Log.d("crackme", hexstr)
            Log.d("crackme", userSN)
            if (!userSN.equals(sn, ignoreCase = true)) return false
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
            return false
        }
        return true
    }

    companion object {
        private fun toHexString(bytes: ByteArray, separator: String): String {
            val hexString = StringBuilder()
            for (b in bytes) {
                val hex = Integer.toHexString(0xFF and b.toInt())
                if (hex.length == 1) {
                    hexString.append('0')
                }
                hexString.append(hex).append(separator)
            }
            return hexString.toString()
        }
    }
}